//package com.plian.system.service.im.impl;
//
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.read.listener.PageReadListener;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.plian.Tools.CacheUtil;
//import com.plian.Tools.CollectionUtil;
//import com.plian.Tools.StringUtil;
//import com.plian.Tools.TokenUtil;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.bean.im.InvestmentDebtInfoImportExcelBean;
//import com.plian.system.dao.pm.property.PropertyBasicsDao;
//import com.plian.system.dao.sys.orgzation.OrgzationDao;
//import com.plian.system.entity.im.InvestmentDebtInfo;
//import com.plian.system.excel.ImportExcelUtil;
//import com.plian.system.excel.ImportResult;
//import com.plian.system.mapper.im.InvestmentDebtInfoMapper;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.service.im.IInvestmentDebtInfoService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.yth.IDebtProjectService;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang.StringUtils;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.scheduling.annotation.AsyncResult;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.ByteArrayInputStream;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.util.*;
//import java.util.concurrent.Future;
//
///**
// * 服务实现类
// */
//@Slf4j
//@Service
//@AllArgsConstructor
//public class InvestmentDebtInfoServiceImpl extends BaseServiceImpl<InvestmentDebtInfoMapper, InvestmentDebtInfo> implements IInvestmentDebtInfoService {
//
//    private OrgzationDao orgzationDao;
//
//    private PropertyBasicsDao propertyBasicsDao;
//
//    @Autowired
//    private IDebtProjectService debtProjectService;
//
//    private ISysUserService userService;
//    private IOrgService orgService;
//
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public boolean saveOrUpdate(InvestmentDebtInfo investmentDebtInfo) {
//        return super.saveOrUpdate(investmentDebtInfo);
//    }
//
//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            InvestmentDebtInfo investmentDebtInfo = getById(id);
//            if (investmentDebtInfo == null) {
//                return false;
//            }
//        }
//        return super.deleteLogic(ids);
//    }
//
//    @Override
//    @Async("ttlExecutor")
//    public Future<ImportResult> importExcel(String progressId, InputStream inputStream) {
//        String progress = "progress";
//        String key = progressId + "#half:hour";
//        try {
//            byte[] bytes = IOUtils.toByteArray(inputStream);
//            inputStream = new ByteArrayInputStream(bytes);
//
//            Map<String, Map<String, String>> mapRef = getRef();
//
//            List<Object> projectList = new ArrayList<>();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(0).headRowNumber(5).head(InvestmentDebtInfoImportExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> projectList.addAll(list))).build());
//            ImportExcelUtil.filterEmpty(projectList);
//            ImportResult result = checkData(mapRef, projectList, progressId);
//            if (!result.isSuccess()) {
//                CacheUtil.put(progress, progress, key, result.getMsg());
//                return new AsyncResult<>(result);
//            }
//
//            int count = 0;
//            int size = projectList.size();
//            // 项目信息
//            for (Object readExcel : projectList) {
//                InvestmentDebtInfo investmentDebtInfo = (InvestmentDebtInfo) ImportExcelUtil.getEntityByExcelBean((InvestmentDebtInfoImportExcelBean) readExcel, new InvestmentDebtInfo());
//
//                LambdaQueryWrapper<InvestmentDebtInfo> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.eq(InvestmentDebtInfo::getCreateCompanyId, TokenUtil.getTokenOrgId());
//                queryWrapper.eq(InvestmentDebtInfo::getProjectName, investmentDebtInfo.getProjectName());
//                InvestmentDebtInfo old = getOne(queryWrapper);
//                if (Optional.ofNullable(old).isPresent()) {
//                    investmentDebtInfo.setId(old.getId());
//                }
//
//                //入库
//                try {
//                    saveOrUpdate(investmentDebtInfo);
//                    count++;
//                    int value = count * 100 / size;
//                    CacheUtil.put(progress, progress, key, value + 100);
//                } catch (Exception e) {
//                    log.error(investmentDebtInfo + "导入失败");
//                    CacheUtil.put(progress, progress, key, investmentDebtInfo + "导入失败");
//                    return new AsyncResult<>(new ImportResult(false, investmentDebtInfo + "导入失败"));
//                }
//            }
//
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            log.error("解析失败");
//            CacheUtil.put(progress, progress, key, "解析失败");
//            return new AsyncResult<>(new ImportResult(false, "解析失败"));
//        }
//
//        CacheUtil.put(progress, progress, key, "导入成功");
//        return new AsyncResult<>(new ImportResult(true, "导入成功"));
//    }
//
//    @Override
//    public String checkName(InvestmentDebtInfo investmentDebtInfo) {
//        if (StringUtil.isBlank(investmentDebtInfo.getProjectName())) {
//            return "项目名称为空";
//        }
//
//        LambdaQueryWrapper<InvestmentDebtInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(InvestmentDebtInfo::getCreateCompanyId, TokenUtil.getTokenOrgId());
//        queryWrapper.eq(InvestmentDebtInfo::getProjectName, investmentDebtInfo.getProjectName());
//        InvestmentDebtInfo old = getOne(queryWrapper);
//
//        if (!Optional.ofNullable(old).isPresent()) {
//            return null;
//        }
//        if (old.getId().equals(investmentDebtInfo.getId())) {
//            return null;
//        }
//        return "该项目名称已存在";
//    }
//
//    @Override
//    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
//        try {
//            String fname = "债务余额与结构项目基本信息导入模板";
//            os = response.getOutputStream();//取得输出流
//            response.reset();//清空输出流
//            //下面是对中文文件名的处理
//            response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
//            InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/InvestmentDebtInfo.xlsx");
//            fname = java.net.URLEncoder.encode(fname, "UTF-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("UTF-8"), "UTF-8") + ".xlsx");
//
//            response.setContentType("application/msexcel");//定义输出类型
//            int len;
//            byte[] b = new byte[2048];
//            while ((len = inputStream.read(b)) != -1) {
//                os.write(b, 0, len);
//            }
//            response.setHeader("Content-Length", String.valueOf(inputStream.available()));
//
//            inputStream.close();
//            os.close();
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//    }
//
//    private Map<String, Map<String, String>> getRef() {
//        Map<String, Map<String, String>> mapRefs = new HashMap<>(16);
//        HashMap<String, String> statusMap = new HashMap<>();
//        HashMap<String, String> categoryMap = new HashMap<>();
////		HashMap<String, String> isFundInvestmentMap = new HashMap<>();
//        statusMap.put("1", "筹建");
//        statusMap.put("2", "在建");
//        statusMap.put("3", "建成");
//        categoryMap.put("1", "自营项目");
//        categoryMap.put("2", "政府性项目");
////		isFundInvestmentMap.put("1","否");
////		isFundInvestmentMap.put("2","是");
//        mapRefs.put("status", statusMap);
//        mapRefs.put("category", categoryMap);
////		mapRefs.put("isFundInvestment",isFundInvestmentMap);
//        Map<String, String> unitRef = new HashMap<>(512);
//        Map<String, String> propertyRef = new HashMap<>(2048);
//        try {
//            List<PageData> allOrgs = orgzationDao.list(null);
//            if (CollectionUtil.isNotEmpty(allOrgs)) {
//                for (PageData pageData : allOrgs) {
//                    unitRef.put((String) pageData.get("name"), (String) pageData.get("id"));
//                }
//
//            }
//            List<PageData> allProperty = propertyBasicsDao.list(null);
//            if (CollectionUtil.isNotEmpty(allProperty)) {
//                for (PageData property : allProperty) {
//                    propertyRef.put((String) property.get("orgName"), (String) property.get("id"));
//                }
//            }
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        mapRefs.put("unitRef", unitRef);
//        mapRefs.put("propertyRef", propertyRef);
//
//
//        return mapRefs;
//    }
//
//    private ImportResult checkData(Map<String, Map<String, String>> mapRef, List<Object> readExcels, String progressId) {
//        ImportResult importResult = new ImportResult(true, "");
//
//        StringBuilder msg = new StringBuilder();
//
//        if (CollectionUtil.isNotEmpty(readExcels)) {
//            for (Object readExcel : readExcels) {
//                InvestmentDebtInfoImportExcelBean excelBean = (InvestmentDebtInfoImportExcelBean) readExcel;
//                int index = readExcels.indexOf(readExcel) + 4;
//
//                //判空
//                msg.append(ImportExcelUtil.checkEmpty("1", "债务项目名称",
//                        excelBean.getProjectName(), index).getMsg());
//                //判空
//                msg.append(ImportExcelUtil.checkEmpty("1", "项目公司",
//                        excelBean.getProjectCompanyId(), index).getMsg());
//
//                //判空
//                String isFundInvestment = excelBean.getIsFundInvestment();
//                if (StringUtils.isEmpty(isFundInvestment)) {
//                    msg.append(ImportExcelUtil.checkEmpty("1", "是否基金投资",
//                            excelBean.getIsFundInvestment(), index).getMsg());
//                } else if ("1".equals(isFundInvestment)) {
//                    //判空
//                    msg.append(ImportExcelUtil.checkEmpty("1", "项目投资建设状况",
//                            excelBean.getConstructionStatus(), index).getMsg());
//                } else if ("2".equals(isFundInvestment)) {
//                    //不填
//                    msg.append(ImportExcelUtil.checkNull("1", "项目投资建设状况",
//                            excelBean.getConstructionStatus(), index).getMsg());
//                } else {
//                    //是否基金投资
//                    msg.append("sheet1第" + index + "行(是否基金投资=" + excelBean.getIsFundInvestment() + ")在系统中不存在\n");
//                }
//
//                //判空
//                msg.append(ImportExcelUtil.checkEmpty("1", "项目性质",
//                        excelBean.getProjectCategory(), index).getMsg());
//
//                //判类型
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_INTEGER, "1", "是否基金投资",
//                        excelBean.getIsFundInvestment(), index).getMsg());
//                //判类型
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_INTEGER, "1", "项目投资建设状况",
//                        excelBean.getConstructionStatus(), index).getMsg());
//                //判类型
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_INTEGER, "1", "项目性质",
//                        excelBean.getProjectCategory(), index).getMsg());
//                //判类型
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "1", "计划总投资（调整后）",
//                        excelBean.getPlanTotalInvestment(), index).getMsg());
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "1", "财政性资金",
//                        excelBean.getFiscalFunds(), index).getMsg());
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "1", "股东资本金",
//                        excelBean.getShareholderCapital(), index).getMsg());
//                msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "1", "项目借款",
//                        excelBean.getProjectLoan(), index).getMsg());
//
//                //判断完类型若有错直接返回
//                if (msg.toString().length() > 0) {
//                    return new ImportResult(false, msg.toString());
//                }
//            }
//            //判断完类型若有错直接返回
//            if (msg.toString().length() > 0) {
//                return new ImportResult(false, msg.toString());
//            }
//
//            //对象和字典是否存在校验
//            int size = readExcels.size();
//            int count = 0;
//            for (Object readExcel : readExcels) {
//                InvestmentDebtInfoImportExcelBean excelBean = (InvestmentDebtInfoImportExcelBean) readExcel;
//                int index = readExcels.indexOf(readExcel) + 6;
//                //对象和字典是否存在校验
//                //单位名称
//                excelBean.setProjectCompanyId(StringUtil.cleanChars(excelBean.getProjectCompanyId()));
//                if (mapRef.get("propertyRef").containsKey(excelBean.getProjectCompanyId())) {
//                    excelBean.setProjectCompanyId(mapRef.get("propertyRef").get(excelBean.getProjectCompanyId()));
//                } else if (!StringUtil.isEmpty(excelBean.getProjectCompanyId())) {
//                    msg.append("sheet1第" + index + "行(项目公司=" + excelBean.getProjectCompanyId() + ")在系统中不存在\n");
//                }
//
//                //项目投资建设状况
//                if (StringUtil.isNotBlank(excelBean.getConstructionStatus())) {
//                    if (!mapRef.get("status").containsKey(excelBean.getConstructionStatus())) {
//                        msg.append("sheet1第" + index + "行(项目投资建设状况=" + excelBean.getConstructionStatus() + ")在系统中不存在\n");
//                    }
//                }
//
//                //项目性质
//                if (StringUtil.isNotBlank(excelBean.getProjectCategory())) {
//                    if (!mapRef.get("category").containsKey(excelBean.getProjectCategory())) {
//                        msg.append("sheet1第" + index + "行(项目性质=" + excelBean.getProjectCategory() + ")在系统中不存在\n");
//                    }
//                }
//
//                count++;
//                int value = count * 100 / size;
//                CacheUtil.put("progress", "progress", progressId, value);
//            }
//        }
//
//        //统一放置报错
//        if (msg.toString().length() > 0) {
//            importResult = new ImportResult(false, msg.toString());
//        }
//        return importResult;
//
//    }
//}
//
